package edu.mtu.citizenscience.streamapplication.activity.main;

import edu.mtu.citizenscience.streamapplication.activity.DBHelper;
import edu.mtu.citizenscience.streamapplication.activity.R;
import edu.mtu.citizenscience.streamapplication.activity.R.layout;
import edu.mtu.citizenscience.streamapplication.activity.R.menu;

import edu.mtu.citizenscience.streamapplication.activity.main.reports.*;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.os.Build;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author Bryan Becker <bcbecker@mtu.edu>
 * @copyright (c) 2013 MichiganTech <http://www.mtu.edu>
 * 
 * Manage Reports Activity that displays a list of all reports in the
 * stream database providing a thumbnail of a picture, the stream name,
 * and the creation date to be displayed to the user. If the user would
 * like to view, edit, or delete a report, they may click on the site
 * in the list.
 */
public class ManageReportsActivity extends ListActivity{

	//create a progress dialog for when we are retrieving the reports
	private ProgressDialog ProgressDialog = null;
	//an array list that will store all our sites to be displayed in Model Reports
	private ArrayList<ModelReport> reports = null;
	//list adapter
	private ReportListAdapter adapter;
	private Runnable viewReports;
	//database helper class
	private DBHelper myDbHelper;
	//custom header bar
	private TextView header;
	
	/**
	 * Manage Reports Activity creation handler
	 * 
	 * @param   savedInstanceState - Bundle - Bundle with launch info
	 * @return	void
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//set the content view and enable the custom title
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_manage_reports);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
		
		//set the custom header text to be "View/Edit Reports"
		header = (TextView) findViewById(R.id.header_text);
		header.setText("View/Edit Reports");
		
		//intialize reports
		reports = new ArrayList<ModelReport>();
		
		//set up our list adapter
		this.adapter = new ReportListAdapter(this, R.layout.row, reports);
		setListAdapter(this.adapter);

		//open our current database
		myDbHelper = new DBHelper(this);
		myDbHelper.open();
		
		//view a list of our reports
		viewReports = new Runnable(){
			@Override
			public void run() {
				getReports();
			}
		};
		
		//start a new thread with view reports
		Thread thread =  new Thread(null, viewReports, "MagentoBackground");
		thread.start();
		
		//set up a progress dialog box to display retrieving data until our reports are done 
		//being retrieved from the database
		ProgressDialog = ProgressDialog.show(ManageReportsActivity.this,    
				"Please wait...", "Retrieving data ...", true);
		
		//set up our on item click listener for when the user clicks a specific site
		getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
			
			//when a site is clicked on in the list
		    public void onItemClick(AdapterView parent, View v, int position, long id){
				// get the report from the list based on its position and then get the id from the report model
				long reportId = reports.get(position).getID();
				
				//start a new Report Guide Activity and give it the row ID and set the variable editing to
				//be true so that we know we are editing and not in site creation
				Intent intent = new Intent(ManageReportsActivity.this, ReportGuide.class);
				intent.putExtra(SCLocationActivity.ROW_ID, reportId);
				intent.putExtra(ReportGuide.EDITING, true);
				startActivity(intent);
				
				//end our Manage Reports Activity (we will recreate after)
				finish();
		    }
		});
	}
	
	//runnable returnRes
	private Runnable returnRes = new Runnable() {

		/**
		 * Run method for our runnable
		 * 
		 * @param   void
		 * @return	void
		 */
		@Override
		public void run() {
			//if there exists a report in the array list
			if(reports != null && reports.size() > 0){
				//notify the data set there is new data
				adapter.notifyDataSetChanged();
				
				//add every report in the array list to the adapter
				for(int i=0;i<reports.size();i++)
					adapter.add(reports.get(i));
			}
			//dismiss our progress dialog prompt when we are done gathering
			//all of our reports
			ProgressDialog.dismiss();
			
			//notify the data set was changed again
			adapter.notifyDataSetChanged();
		}
	};
	
	/**
	 * Method to get reports from the database and store them
	 * in our reports array list as Model Reports
	 * 
	 * @param   void
	 * @return	void
	 */
	private void getReports(){
		
		//try to fetch the list of reports from the database
		try{
			reports = myDbHelper.fetchList();
		} catch (Exception e) {
			//throw a log that we could not retrieve the list of reports from the database
        	Log.w("Manage Reports Activity", "Could not fetch the list of reports to be displayed.");
		}
		runOnUiThread(returnRes);
	}
	
	/**
	 * onClick activity for the Tutorial button.
	 * 
	 * @param view - View - responsible for drawing UI components and event handling
	 * @return	void
	 */
	public void tutorial(View view) {
		//start a new Tutorial Activity
		this.startActivity(new Intent(this, SCTutorialActivity.class));
	}

	/**
	 * An internal class that represents our report list adapter that is
	 * connected to every report in the list so that when the user clicks
	 * on a report, it brings them to the next activity.
	 */
	public class ReportListAdapter extends ArrayAdapter<ModelReport> {

		//array list of Model Reports
	    private ArrayList<ModelReport> reports;

		/**
		 * Report List Adapter constructor
		 * 
		 * @param context - Context - current state of the application
		 * @param textViewResourceId - int - the resource id for our text view
		 * @param reports - ArrayList<ModelReport> - array list of model reports to display
		 */
	    public ReportListAdapter(Context context, int textViewResourceId, ArrayList<ModelReport> reports) {
	            super(context, textViewResourceId, reports);
	            this.reports = reports;
	    }

		/**
		 * Get the view for our report list adapter
		 * 
		 * @param position - int - current position in our list of reports
		 * @param convertView - View - an individual view for each report in the list
		 * @param parent - ViewGroup - view container
		 * @return View - return the
		 */
	    public View getView(int position, View convertView, ViewGroup parent) {
	    		//if convert view doesn't exist
	            if (convertView == null) {
	            	//set the convert view to our row.xml 
	                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	                convertView = vi.inflate(R.layout.row, null);
	            }
	            
	    	    // get the model report that this view is displaying in the list
	    	    ModelReport report = this.getItem(position);
	    	    
	    	    // set the report time in our convert view to be the time of creation in our Model Report
        	    ((TextView) convertView.findViewById(R.id.reportTime)).setText(report.getDate());

        	    //set the report stream name in our convert view to be the stream name in our Model Report
	    	    ((TextView) convertView.findViewById(R.id.reportStreamName)).setText(report.getStreamName());
	    	    
	    	    //return our convert view
	            return convertView;
	    }
	}
	
}